package TCPEcho;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoSever {
    private ServerSocket serverSocket = null;
    //创建服务器需要手动指定端口号
    public TcpEchoSever(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");

        while(true){
            //TCP是有连接的
            //需要accept方法来接听电话,然后才能进行通信
            //在主线程中进行accept
            Socket clineSocket = serverSocket.accept();

            ExecutorService pool = Executors.newCachedThreadPool();
            //创建新的线程给服务器提供服务
//            Thread t = new Thread(()->{
//                try {
//            +        processConnetion(clineSocket);
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            });
//            t.start();
            pool.submit(()->{
                try {
                    processConnetion(clineSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    //通过这个方法来处理一次连接，连接建立的过程中就会涉及到多次的请求响应交互
    //有连接，所以需要保存对端的信息
    private void processConnetion(Socket clineSocket) throws IOException {
        System.out.printf("[%s:%d],客户端上线！\n",clineSocket.getInetAddress(),clineSocket.getPort());
        //循环读取客户端的请求并返回响应
        try (InputStream inputStream = clineSocket.getInputStream();
             OutputStream outputStream = clineSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            while(true){
                if(!scanner.hasNext()){
                    System.out.printf("[%s:%d],客户端下线！\n",clineSocket.getInetAddress(),clineSocket.getPort());
                    break;
                }
            //1、读取请求并解析，这里注意隐藏的约定，next读的时候要读到空白符才会结束
                // 因此客户端发来的请求必须要以空白符结尾,因此必须要带有换行或者空格
            String request = scanner.next();
            //2、根据请求计算响应
            String response = process(request);
            //3、把响应返回给客户端
          // 可以通过这种方式进行返回，但是这种方式不太容易添加换行
         //  outputStream.write(response.getBytes(),0,response.getBytes().length);
                // 可以给outputStream包装下，完成写入
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                //手动刷新缓冲区，确保数据发送
                printWriter.flush();
                System.out.printf("[%s:%d],req:%s,resp:%s",clineSocket.getInetAddress(),clineSocket.getPort(),request,response);
            }
        }finally {
            clineSocket.close();
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoSever tcpEchoSever = new TcpEchoSever(9090);
        tcpEchoSever.start();
    }
}
